<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 栅格布局 -->
      <!-- 顶部输入框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <div>
              <el-input placeholder="请输入用户名" @input="deletstrfun" clearable v-model="inputvalue"
                class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="checkuserid"></el-button>
              </el-input>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="adduserfun">添加用户</el-button>
          </div>
          <!-- 添加用户 -->
          <template>
            <el-dialog title="添加用户" :visible.sync="dialogFormVisible3">
              <!-- :rules="loginRules" -->
              <el-form :model="info" :rules="rules" ref="info" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
                  <el-input v-model="info.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
                  <el-input v-model="info.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
                  <el-input v-model="info.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
                  <el-input v-model="info.mobile" autocomplete="off"></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible3 = false">取 消</el-button>
                <!-- ($event, scope.row, scope.$index) (状态true/false，当前行数据，索引) -->
                <el-button type="primary" @click="adduserinfo">确
                  定</el-button>
              </div>
            </el-dialog>
          </template>
        </el-col>
      </el-row>
      <!-- 渲染数据部分 -->
      <el-table :data="tableData" v-if="tableData" border style="width: 100%">
        <el-table-column type="index" align="center" width="50">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- template标签中使用 slot-scope='scpoe' -->
            <!-- el-switch 使用  v-model="scope.row.字段"-->
            <!-- changestate($event, scope.row, scope.$index) (状态true/false，当前行数据，索引) -->
            <el-switch v-model="scope.row.mg_state" @change="changestate($event, scope.row, scope.$index)"
              active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">

            <el-button type="primary" icon="el-icon-edit" size="small"
              @click="opentable(scope.row, scope.$index)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="deletopen(scope.row)"></el-button>
            <el-button type="warning" icon="el-icon-setting" size="small"
              @click="fenpeiopen(scope.row, scope.$index)"></el-button>
            <!-- 修改用户-弹出对话框start -->
            <el-dialog title="修改用户" :visible.sync="dialogFormVisible">
              <el-form :model="tableData[changeindex]" :rules="rules2" ref="tableData[changeindex]"
                class="demo-ruleForm">
                <el-form-item label="用户名" :label-width="formLabelWidth">
                  <el-input disabled v-model="tableData[changeindex].username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
                  <el-input v-model="tableData[changeindex].email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
                  <el-input v-model="tableData[changeindex].mobile" autocomplete="off"></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <!-- ($event, scope.row, scope.$index) (状态true/false，当前行数据，索引) -->
                <el-button type="primary"
                  @click="changinfo(tableData[changeindex].id, tableData[changeindex].email, tableData[changeindex].mobile)">确
                  定</el-button>
              </div>
            </el-dialog>
            <!-- 弹出对话框end -->
            <!-- 更新角色 对话框start -->
            <el-dialog title="分配角色" :visible.sync="dialogFormVisible2">
              <el-form>
                <el-form-item label="当前的用户:" :label-width="formLabelWidth">
                  <span>{{ tableData[changeindex].username }}</span>
                  <!-- <el-input v-model="tableData[changeindex].username" autocomplete="off"></el-input> -->
                </el-form-item>
                <el-form-item label="当前的角色:" :label-width="formLabelWidth">
                  <span>{{ tableData[changeindex].role_name }}</span>
                  <!-- <el-input v-model="tableData[changeindex].role_name" autocomplete="off"></el-input> -->
                </el-form-item>
                <!-- <el-input v-model="tableData[changeindex].mobile" autocomplete="off"></el-input> -->
                <el-form-item label="分配新角色:" :label-width="formLabelWidth">
                  <el-select v-model="newrole" placeholder="请选择角色">
                    <el-option label="主管" value=30></el-option>
                    <el-option label="经理" value=31></el-option>
                    <el-option label="副经理" value=34></el-option>
                    <el-option label="组长" value=39></el-option>
                    <el-option label="副组长" value=40></el-option>
                    <el-option label="组员" value=41></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible2 = false">取 消</el-button>
                <!-- ($event, scope.row, scope.$index) (状态true/false，当前行数据，索引) -->
                <el-button type="primary"
                  @click="fenpeiinfo(tableData[changeindex].id, tableData[changeindex].username)">确
                  定</el-button>
              </div>
            </el-dialog>
            <!-- 更新角色 对话框end -->

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[3, 4, 6]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="totalnum">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputvalue: '',//输入框绑定的数据
      tableData: [],//用户数据
      pageSize: 3,//控制每页可以显示多少条数据
      currentPage: 1,//当前页数
      totalnum: 1,// 总条数
      // 
      dialogFormVisible: false,
      formLabelWidth: '120px',
      changeindex: 0,//负责修改用户信息对话框的索引
      dialogFormVisible2: false,
      newrole: '',//新角色属性
      dialogFormVisible3: false,//添加用户对话框flag
      info: {//需要添加的用户信息
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      checkList: [],//查询所有数据
      // 校验
      rules: {
        username: [
          { required: true, message: '帐号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' }
        ],
      },
      rules2: {
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' }
        ],
      }
    }
  },
  // 初始化钩子函数
  // 发起请求
  created() {
    this.getuserList()//初始化获取用户数据
  },
  methods: {
    // 1.获取用户数据列表
    async getuserList() {
      // 获取用户数据列表
      let res = await this.$http({
        method: 'get',
        url: "users",
        // query: this.inputvalue,
        params: {//请求参数
          pagenum: this.currentPage,//当前页码页数
          pagesize: this.pageSize,//每页显示条数
        }
      })
      console.log(res);
      this.totalnum = res.data.data.total//获取总条数
      this.tableData = res.data.data.users//获取用户数据
      console.log(this.tableData);
      this.changeindex = 0

    },
    // 当条数改变时触发该回调回调函数 val为控制每页可以显示多少条数据
    handleSizeChange(val) {
      console.log(val);
      this.pageSize = val
      this.getuserList()//重新调用获取用户数据列表
    },
    //当页数改变时触发该回调函数 val为当前页数
    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val
      this.getuserList()//重新调用获取用户数据列表
    },
    // 开关按钮事件
    async changestate(e, row, index) {
      console.log('状态：' + e);
      console.log(row);//请求修改用户状态需要用户id row.id
      console.log('索引：' + index);
      // 2.修改用户状态
      let res = await this.$http({//发起修改用户状态
        method: 'PUT',
        url: 'users/' + row.id + '/state/' + e,
      })
      console.log(res);
      console.log(res.data.meta.msg);
      if (res.data.meta.status == 200) {//判断返回值
        this.opensucces(res.data.meta.msg)
      }
    },
    // 3.根据用户id进行查询(待定有问题 请求回来的数据不是想要的)
    // 通过姓名去查找 点击事件  绑定input事件 当值长度为0 重新调用渲染数据
    // 一页数据通过 总条数获取整体的一页数据 通过遍历筛选出出需要的数据
    // 将其添加到渲染数组中
    async checkuserid() {
      let res = await this.$http({
        method: 'get',
        url: "users",
        params: {//请求参数 获取所有数据
          pagenum: 1,//当前页码页数
          pagesize: this.totalnum//每页显示条数
        }
      })
      // 将所有数据进行存储
      this.checkList = res.data.data.users
      // 遍历出需要的数组
      this.checkList = this.checkList.filter(obj => obj.username == this.inputvalue)
      console.log(this.checkList);
      if (this.checkList.length == 0) {
        this.openerror('没得该人！')
      } else {
        this.opensucces('查询成功')
        this.tableData = this.checkList
      }
    },
    // input事件当为空时重新调用查询用户数据函数
    deletstrfun() {
      if (this.inputvalue.length == 0) {
        this.getuserList()//重新渲染
      }
    },
    // 成功弹出提醒
    opensucces(val) {
      this.$message({
        message: val,
        type: 'success'
      });
    },
    // 失败弹出提醒
    openerror(val) {
      this.$message.error(val);
    },
    // 修改用户信息
    async changinfo(id, email, mobile) {
      console.log(id);//用户id
      console.log(email);//email
      console.log(mobile);//mobile
      if (email.length == 0 && mobile.length == 0) {
        return
      }
      this.dialogFormVisible = false
      let res = await this.$http({//发起修改用户请求
        url: 'users/' + id,
        method: 'put',
        data: {
          email: email,
          mobile: mobile
        }
      })
      console.log(res);
      if (res.status === 200) {
        this.changeindex = 0
        this.opensucces(res.data.meta.msg)//成功提示
      } else {
        this.openerror(res.data.meta.msg)//失败提示
      }
    },
    // 4.打开修改用户信息对话框
    opentable(row, index) {
      console.log(index);
      console.log(row);
      console.log(this.tableData);
      this.changeindex = index
      this.dialogFormVisible = true
    },
    //5. 删除用户提示框
    deletopen(res) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log(res);//获取到那个用户需要删除信息
        if (res.username === "admin") {
          this.$message({
            type: 'error',
            message: 'admin用户不允许删除!'
          });
          return
        } else {
          let back = await this.$http({//删除请求
            url: 'users/' + res.id,
            method: 'delete'
          })
          console.log(back);
          if (back.data.meta.status === 200) {
            // 这里需要做一个判断
            // 如果删除的数据是第二页剩下的最后一个数据需要将
            // 页数减一在发送请求
            // pageSize: 3,//控制每页可以显示多少条数据
            // currentPage: 1,//当前页数
            //  totalnum: 1,// 总条数
            if ((this.totalnum % this.pageSize === 1) && (Math.floor(this.totalnum / this.pageSize) !== this.currentPage)) {
              this.currentPage = this.currentPage - 1
            }
            this.getuserList()//重新调用渲染函数
            this.$message({//如果成功
              type: 'success',
              message: back.data.meta.msg
            });
            return
          } else {//如果失败
            console.log(error);
            this.$message({
              type: 'error',
              message: back.data.meta.msg
            });
            return
          }
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 打开分配新角色弹框
    fenpeiopen(row, index) {
      console.log(row);
      console.log(index);
      this.changeindex = index
      this.dialogFormVisible2 = true
    },
    // 分配新角色
    async fenpeiinfo(id, name) {
      console.log(id);
      this.dialogFormVisible2 = false
      if (name === 'admin') {//简单判定 
        this.openerror('admin不允许修改')
        this.newrole = ''
        return
      }
      let res = await this.$http({//发起角色分配请求
        url: 'users/' + id + '/role',
        method: 'PUT',
        data: {
          rid: this.newrole
        }
      })
      if (res.data.meta.status === 200) {//判断返回结果
        this.getuserList()
        this.opensucces(res.data.meta.msg)//调用提示信息
        this.newrole = ''
      } else {
        this.openerror(res.data.meta.msg)//调用提示信息
        this.newrole = ''
      }
    },
    // 添加用户
    adduserfun() {
      this.dialogFormVisible3 = true
    },
    async adduserinfo() {
      if (this.info.username.length == 0 && this.info.email.length == 0 && this.info.password.length == 0 && this.info.mobile.length == 0) return
      this.dialogFormVisible3 = false
      let res = await this.$http({//发起添加用户请求
        url: 'users',
        method: 'post',
        data: { ...this.info }
      })
      console.log(res);
      this.info.username = ''//清空数据
      this.info.password = ''
      this.info.email = ''
      this.info.mobile = ''
      if (res.data.meta.status === 201) {//判断返回值
        this.getuserList()
        this.opensucces(res.data.meta.msg)//调用提示信息
      } else {
        this.openerror(res.data.meta.msg)
      }
    },
  }
}
</script>

<style lang="less" scoped>

</style>
